#coding:utf-8
'''
模块管理器：
    维护一个模块列表
'''
from PySide6.QtCore import QObject
import os
import inspect 
import sys 
class ModuleManager(QObject):
    
    def __init__(self,mainPanel):
        super().__init__()

        self.settingsPath = "settings.json"

        self.modules = [] ## module list 
        self.moduleFolder = 'modules' ## module保存的文件夹路径
        self.moduleState = {} ## 记录moduleName: state
        self.moduleClses = {} ## moduleName: class
        self.moduleObj = {} ## moduleName: obj

        self.mainPanel = mainPanel
        
        self.scanAllModules()
    
    def scanAllModules(self):
        for path in os.listdir(self.moduleFolder):
            modulePath = os.path.join(self.moduleFolder,path)
            foundClses = self.scanModule(modulePath)
            self.moduleClses.update(foundClses)

    def scanModule(self,modulePath):
        '''
        modulepath 是module对应的文件夹
        '''
        foundClses = {}
        if os.path.isdir(modulePath):
            sys.path.append(modulePath)
            for pyfile in os.listdir(modulePath):
                #判断是否是python文件
                if not '.py' in pyfile or pyfile == "__init__.py" or pyfile.startswith(
                        '__init__'):
                    continue
                #获得python文件地址
                moduleName = pyfile[:-3]
                __import__(moduleName, locals(), globals())
                for cls_name, cls in inspect.getmembers(
                        sys.modules[moduleName], inspect.isclass):
                    if cls_name != 'BaseModule' and issubclass(
                            cls, BaseModule):
                        print(f'module found: {cls_name}')
                        foundClses[cls.Name] = cls
        return foundClses
    
    def loadAllModules(self):
        for name in self.moduleClses.keys():
            self.loadModule(name)

    def loadModule(self,moduleName):
        '''
        加载模块
        '''
        moduleCls = self.moduleClses[moduleName]
        moduleObj = moduleCls(self.mainPanel,self)
        moduleObj.load()
        self.moduleObj[moduleName] = moduleObj

    def removeModule(self,moduleName):
        '''删除模块'''
        obj = self.moduleObj.pop(moduleName)
        obj.remove()
        

    def removeAllModules(self):
        for name in list(self.moduleObj.keys()):
            self.removeModule(name)


class BaseModule(QObject):
    '''
    所有module的基类
    '''
    Name = 'BaseModule'
    
    def __init__(self,panel,manager):
        super().__init__()
        self.panel = panel
        self.manager = manager

    def load(self):
        print(f'Module {self.Name} loaded') 

    def remove(self):
        print(f'Module {self.Name} removed')





